package com.ting.template.core.common.utils;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * Created by 雷霆 on 2017/12/02.
 */
public final class ThreadUtil {

    public static final int THREAD_POOL_COUNT =Runtime.getRuntime().availableProcessors();

    public static void shutdownAndWaitRunOver(ExecutorService executor) {
        shutdownAndWaitRunOver(executor, 10);
    }



    /**
     * 停止线程池,并等待线程池中的任务跑完
     *
     * @param executor
     * @param time
     */
    public static void shutdownAndWaitRunOver(ExecutorService executor, long time) {
        executor.shutdown();
        while (!executor.isTerminated()) {
            sleep(time);
        }
    }

    public static InterruptedException sleep(long time) {
        try {
            Thread.sleep(time);
        } catch (InterruptedException e) {
            return e;
        }
        return null;
    }

    /**
     * 获取堆栈中clazz以上的一个
     * @param stackTrace
     * @param clazz
     * @return
     */
    public static StackTraceElement getLastStackTraceElement(StackTraceElement[] stackTrace, Class clazz) {
        for (StackTraceElement element : stackTrace) {
            if (!element.getClassName().equals(clazz.getName())) {
                return element;
            }
        }
        if (stackTrace.length > 0) {
            return stackTrace[0];
        }
        return null;
    }


    public static ThreadPoolExecutor getThreadPoolExecutor(int threadCount){
       return  new ThreadPoolExecutor(threadCount,threadCount,
                0L, TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<Runnable>());
    }
}
